package com.nhc.activity_fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.AccelerateInterpolator;

import com.astrob.activitys.GPSProvider;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.nhc.model.CompassDatainfo;
import com.nhc.model.TripItem;
import com.nhc.view.CompassView;
import com.nhc.view.TripItemViewLayout;

import zuo.biao.library.base.BaseActivity;

/**
 * 使用方法：复制>粘贴>改名>改代码
 */

/**
 * fragment示例
 *
 * @use new DemoFragment(),具体参考.DemoFragmentActivity(initData方法内)
 */
public class CompassActivity extends BaseActivity implements View.OnClickListener {
    private final String TAG = "CompassActivity";

    //与Activity通信<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 创建一个Fragment实例
     *
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, CompassActivity.class);
    }

    @Override
    public Activity getActivity() {
        return null;
    }

    //与Activity通信>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.compass_activity);

        initView();
        initData();
        initEvent();
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private TripItemViewLayout tripiemview_0;
    private TripItemViewLayout tripiemview_1;
    private CompassView mPointer;

    @Override
    public void initView() {//必须在onCreateView方法内调用
        tripiemview_0 = (TripItemViewLayout) findViewById(R.id.tripiemview_0);
        tripiemview_1 = (TripItemViewLayout) findViewById(R.id.tripiemview_1);
        mPointer = (CompassView) findViewById(R.id.compass_pointer);
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private CompassDatainfo compassDatainfo = new CompassDatainfo();

    private final float MAX_ROATE_DEGREE = 1.0f;
    private SensorManager mSensorManager;
    private Sensor mOrientationSensor;
    private float mDirection;
    private float mTargetDirection;
    private AccelerateInterpolator mInterpolator;
    protected final Handler mHandler = new Handler();
    private boolean mStopDrawing;

    private GPSProvider mGpsProvider;

    @Override
    public void initData() {//必须在onCreateView方法内调用
        mDirection = 0.0f;
        mTargetDirection = 0.0f;
        mInterpolator = new AccelerateInterpolator();
        mStopDrawing = true;

        mGpsProvider = GPSProvider.getInstance();
        refreshData();
    }

    private void refreshData() {
        String AA[] = SysUtils.getInstance().getAltitudeStr(mGpsProvider.getAltitude());
        tripiemview_0.bindView(new TripItem(getString(R.string.hbgd), AA[0], AA[1]));
        tripiemview_1.bindView(new TripItem(getString(R.string.dqmb), compassDatainfo.getAzimuthstr(), " "));
    }

    protected Runnable mCompassViewUpdater = new Runnable() {
        @Override
        public void run() {
            if (mPointer != null && !mStopDrawing) {
                if (mDirection != mTargetDirection) {

                    // calculate the short routine
                    float to = mTargetDirection;
                    if (to - mDirection > 180) {
                        to -= 360;
                    } else if (to - mDirection < -180) {
                        to += 360;
                    }

                    // limit the max speed to MAX_ROTATE_DEGREE
                    float distance = to - mDirection;
                    if (Math.abs(distance) > MAX_ROATE_DEGREE) {
                        distance = distance > 0 ? MAX_ROATE_DEGREE : (-1.0f * MAX_ROATE_DEGREE);
                    }

                    // need to slow down if the distance is short
                    mDirection = normalizeDegree(mDirection
                            + ((to - mDirection) * mInterpolator.getInterpolation(Math
                            .abs(distance) > MAX_ROATE_DEGREE ? 0.4f : 0.3f)));
                    mPointer.updateDirection(mDirection);
                }

                updateDirection();
                refreshData();

                mHandler.postDelayed(mCompassViewUpdater, 20);
            }
        }
    };

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreateView方法内调用
//        tripiemview_0.setOnClickListener(this);
//        tripiemview_1.setOnClickListener(this);

        initServices();
    }

    private void initServices() {
        // sensor manager
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//        mOrientationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);

    }

    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void onClick(View v) {//直接调用不会显示v被点击效果
        switch (v.getId()) {
            case R.id.tripiemview_0:
                break;
            case R.id.tripiemview_1:
                break;
            default:
                break;
        }
    }

    public static final String RESULT_VALUE = "RESULT_VALUE";

    @Override
    public void onForwardClick(View v) {
        intent = new Intent();
        intent.putExtra(RESULT_VALUE, compassDatainfo.getAzimuth());
        setResult(RESULT_OK, intent);
        exitAnim = zuo.biao.library.R.anim.left_push_out;
        finish();
    }

    //类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void onResume() {
        super.onResume();

        Sensor gsensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        Sensor msensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        mSensorManager.registerListener(mOrientationSensorEventListener, gsensor, SensorManager.SENSOR_DELAY_GAME);
        mSensorManager.registerListener(mOrientationSensorEventListener, msensor, SensorManager.SENSOR_DELAY_GAME);

        mStopDrawing = false;
        mHandler.postDelayed(mCompassViewUpdater, 20);
    }

    @Override
    public void onPause() {
        super.onPause();
        mStopDrawing = true;
        mSensorManager.unregisterListener(mOrientationSensorEventListener);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void updateDirection() {
        float direction = normalizeDegree(mTargetDirection * -1.0f);
        if (direction > 22.5f && direction < 157.5f) {
            // east
            compassDatainfo.setDirname("东");
        } else if (direction > 202.5f && direction < 337.5f) {
            // west
            compassDatainfo.setDirname("西");
        }

        if (direction > 112.5f && direction < 247.5f) {
            // south
            compassDatainfo.setDirname("南");
        } else if (direction < 67.5 || direction > 292.5f) {
            // north
            compassDatainfo.setDirname("北");
        }

        compassDatainfo.setAzimuth((int) direction);
    }

    private void updateLocation(Location location) {
        if (location == null) {
//            mLocationTextView.setText(R.string.getting_location);
            showShortToast(R.string.getting_location);
        } else {
            StringBuilder sb = new StringBuilder();
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            compassDatainfo.setCurrentvel(location.getSpeed() * 3.6f);

            if (latitude >= 0.0f) {
                sb.append(getString(R.string.location_north, getLocationString(latitude)));
            } else {
                sb.append(getString(R.string.location_south, getLocationString(-1.0 * latitude)));
            }

            sb.append("    ");

            if (longitude >= 0.0f) {
                sb.append(getString(R.string.location_east, getLocationString(longitude)));
            } else {
                sb.append(getString(R.string.location_west, getLocationString(-1.0 * longitude)));
            }

//            mLocationTextView.setText(sb.toString());
            showShortToast(sb.toString());
        }
    }

    private String getLocationString(double input) {
        int du = (int) input;
        int fen = (((int) ((input - du) * 3600))) / 60;
        int miao = (((int) ((input - du) * 3600))) % 60;
        return String.valueOf(du) + "°" + String.valueOf(fen) + "'" + String.valueOf(miao) + "\"";
    }

    private float[] mGData = new float[3];
    private float[] mMData = new float[3];
    private float[] mR = new float[16];
    private float[] mI = new float[16];
    private float[] mOrientation = new float[3];
    private int mCount;

    private SensorEventListener mOrientationSensorEventListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            int type = event.sensor.getType();
            float[] data;
            if (type == Sensor.TYPE_ACCELEROMETER) {
                data = mGData;
            } else if (type == Sensor.TYPE_MAGNETIC_FIELD) {
                data = mMData;
            } else {
                // we should not be here.
                return;
            }
            for (int i = 0; i < 3; i++)
                data[i] = event.values[i];

            if (!SensorManager.getRotationMatrix(mR, mI, mGData, mMData)) {
                return;
            }
            SensorManager.getOrientation(mR, mOrientation);
            float incl = SensorManager.getInclination(mI);
            if (mCount++ > 50) {
                final float rad2deg = (float) (180.0f / Math.PI);
                mCount = 0;
                float degree = (float) ((360f + mOrientation[0] * rad2deg) % 360);
                float direction = degree * -1.0f;
                mTargetDirection = normalizeDegree(direction);
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };

    private float normalizeDegree(float degree) {
        return (degree + 720) % 360;
    }


    //类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


}